package com.zhongxi.guoyuan.fragment.beautifulStoreOrder;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Contacts;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.beautifulStoreOrder.StoreOrderHasNoApplyAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseFragment;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.beautifulOrder.BeautifulStoreOrderData;
import com.zhongxi.guoyuan.entity.beautifulOrder.BeautifulStoreOrderResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.UiUtils;
import com.zhongxi.guoyuan.view.MainActivity;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * A simple {@link Fragment} subclass.
 */
public class StoreOrderHasNoApplyFragment extends BaseFragment implements AdapterView.OnItemClickListener, OnRefreshListener2<ListView> {

    public static final int RESULTCODE = 0201;
    private PullToRefreshListView lvList;
    private StoreOrderHasNoApplyAdapter adapter;
    private List<BeautifulStoreOrderData> data = new ArrayList<>();
    private BeautifulStoreOrderResult result;
    private String type;
    private Map<String, String> map = new HashMap<>();
    private ListView listView;
    private int pos;
    private JSONObject shopInfo;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_beautyorder_has_no_apply, container, false);
    }

    @Override
    protected void initView() {
        super.initView();
        lvList = (PullToRefreshListView) getView().findViewById(R.id.lvList);
        lvList.setMode(PullToRefreshBase.Mode.BOTH);
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            pos = (int) msg.obj;
            switch (msg.what) {
                case 0:
                    showMeidouNoBalance();
                    break;
                case 1:
                    deleteItem();
                    break;
            }
        }
    };


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden)
            getOrderData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /**
     * 美豆余额不足
     */
    private void showMeidouNoBalance() {
        LayoutInflater inflater = LayoutInflater.from(context);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_pay, null);
        final AlertDialog dialog = new AlertDialog.Builder(context).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.getWindow().setContentView(layout);
        TextView tvSurePay = (TextView) layout.findViewById(R.id.tvSurePay);
        TextView tvGouwu = (TextView) layout.findViewById(R.id.tvGouwu);
        ImageView ivCancel = (ImageView) layout.findViewById(R.id.ivCancel);
        //放弃支付
        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        tvSurePay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        tvGouwu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                getActivity().setResult(RESULTCODE);
                getActivity().finish();
            }
        });
    }


    private void deleteItem() {
        type = "cancel";
        map.put("orderid", data.get(pos).getId());
        getServer(Url.NOPAYMENT_DELETE, map, "", false, null, "post");
    }

    @Override
    protected void initData() {
        super.initData();
        adapter = new StoreOrderHasNoApplyAdapter(context, data, handler, this);
        lvList.setAdapter(adapter);
        getOrderData();
        TextView tv = new TextView(context);
        tv.setGravity(Gravity.CENTER);
        tv.setText("亲,你还没有待支付数据哟!");
        tv.setTextSize(20);
        //当界面为空的时候显示的视图
        lvList.setEmptyView(tv);
    }

    private void getOrderData() {
        type = "order";
        String str = "&page=" + pageNum;
        getServer(Url.NOPAYMENT_ORDER, null, str, false, null, "get");
    }


    @Override
    protected void initEvent() {
        super.initEvent();
        lvList.setOnItemClickListener(this);
        lvList.setOnRefreshListener(this);
        listView = lvList.getRefreshableView();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position - 1 == adapter.getmExpandedMenuPos()) {
            adapter.setmExpandedMenuPos(-1);
        } else {
            adapter.setmExpandedMenuPos(position - 1);
        }
        adapter.notifyDataSetChanged();
        listView.setSelection(position);
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try {
            if ("order".equals(type)) {
                result = gson.fromJson(response, BeautifulStoreOrderResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                if (pageNum == 1) {
                    data.clear();
                }
                JSONObject jsonObject = new JSONObject(response);
                if (result.getData() != null && result.getData().size() > 0) {
                    data.addAll(result.getData());
                    shopInfo = jsonObject.optJSONObject("shopInfo");
                    adapter.setShopInfo(shopInfo);
                }
                lvList.onRefreshComplete();
                adapter.notifyDataSetChanged();
            } else if ("cancel".equals(type)) {
                BaseResponse baseResponse = gson.fromJson(response, BaseResponse.class);
                if (baseResponse.getSafeobj() != null && "".equals(baseResponse.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(baseResponse.getSafeobj());
                }
                data.remove(pos);
                adapter.notifyDataSetChanged();

//                deletePattern(listView.getChildAt(pos),pos);
                getOrderData();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try {
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if (null != result.getSafeobj() && !"".equals(result.getSafeobj()))
                MyApplication.getInstance().setSpValue(result.getSafeobj());

            if (type.equals("order")) {
                if (result.getCode() == 1201) {
                    showShortToast("店铺已关闭");
                }
            }

            lvList.onRefreshComplete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum = 1;
        getOrderData();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum++;
        getOrderData();
    }

    private void deletePattern(final View view, final int position) {

        Animation.AnimationListener al = new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                data.remove(position);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        };
        collapse(view, al);

    }

    private void collapse(final View view, Animation.AnimationListener al) {
        final int originHeight = view.getMeasuredHeight();

        Animation animation = new Animation() {
            @Override
            protected void applyTransformation(float interpolatedTime, Transformation t) {
                if (interpolatedTime == 1.0f) {
                    view.setVisibility(View.GONE);
                } else {
                    view.getLayoutParams().height = originHeight - (int) (originHeight * interpolatedTime);
                    view.requestLayout();
                }
            }

            @Override
            public boolean willChangeBounds() {
                return true;
            }
        };
        if (al != null) {
            animation.setAnimationListener(al);
        }
        animation.setDuration(5000);
        view.startAnimation(animation);
    }
}
